import java.util.StringTokenizer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class UpdateManager implements Runnable {
	TransactionManager manager;
	CorporateDatabase db;
	
    public static final String QUEUE_NAME = "UpdateQueue";
	
	public UpdateManager(TransactionManager manager, Resource db) {
		this.manager = manager;
		this.db = (CorporateDatabase)db;
		
		(new Thread(this)).start();
	}

	public void run() {
		Context                 jndiContext = null;
	    QueueConnectionFactory  queueConnectionFactory = null;
	    QueueConnection         queueConnection;
	    QueueSession            queueSession;
	    Queue                   inQueue = null;
	    QueueReceiver           queueReceiver;
	    TextMessage             message;
	    Message					m;
	    
	    System.out.println("Starting UpdateQueue Message Receiver..");
        try {
            jndiContext = new InitialContext();
        } catch (NamingException e) {
            System.out.println("Could not create JNDI API " +
                "context: " + e.toString());
            System.exit(1);
        }
       
        /*
         * Look up connection factory and queue.  If either does
         * not exist, exit.
         */
        try {
            queueConnectionFactory = (QueueConnectionFactory)
                jndiContext.lookup("jms/ConnectionFactory");
            inQueue = (Queue) jndiContext.lookup(QUEUE_NAME);
        } catch (NamingException e) {
            System.out.println("JNDI API lookup failed: " +
                e.toString());
            System.exit(1);
        }

        /*
         * Create connection.
         * Create session from connection; false means session is
         * not transacted.
         * Create receiver, then start message delivery.
         * Receive all text messages from queue until
         * a non-text message is received indicating end of
         * message stream.
         * Close connection.
         */
        try {
            queueConnection =
                queueConnectionFactory.createQueueConnection("guest","guest");
            queueSession =
                queueConnection.createQueueSession(false,
                    Session.AUTO_ACKNOWLEDGE);
            queueReceiver = queueSession.createReceiver(inQueue);
            queueConnection.start();
           
            System.out.println("Listening to queue " + QUEUE_NAME + "....");
           
            while (true) {
                m = queueReceiver.receive(1);
                
                if (m != null) {
                    if (m instanceof TextMessage) {
                        message = (TextMessage) m;
                       
                        System.out.println("Message Received... processing");
                        System.out.println(message.getText());
                        System.out.println();
                        
                        processUpdate(message.getText());

                    } else {
                        break;
                    }
                }
            }       
        } catch (JMSException e) {
            System.out.println("Exception occurred: " +
                e.toString());
        }
	}
	
	private void processUpdate(String xml) {
        StringTokenizer tokenizer;
        String 			query = "";
        String			uid;
        
        tokenizer = new StringTokenizer(xml,"\"");
		
		if (xml.indexOf("<Update name=") > -1) {
			//UID will be the 4th token
			for(int j = 0; j <= 2; j++) 
				tokenizer.nextToken();
			uid = tokenizer.nextToken();
			System.out.println("Request Installation Update- UID: " + uid + "\t...now closed");
			
			query += 	"UPDATE service_request_log " +
						"SET service_status='C' " +
						"WHERE service_number=" + uid + ";";
			
			db.execute(query);
		}
		else {
			//UID will be the 2nd token
			tokenizer.nextToken();
			uid = tokenizer.nextToken();
			System.out.println("Trouble Ticket Update- UID: " + uid + "\t...now closed");
			
			query += 	"UPDATE trouble_ticket_log " +
						"SET ticket_status='C' " +
						"WHERE ticket_number=" + uid + ";";

			db.execute(query);
		}
	}
}
